import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:xinxuan/common/dialogs/delivery_confirmation_dialog.dart';
import 'package:xinxuan/common/dialogs/message_dialog.dart';
import 'package:xinxuan/controllers/store_order_controller/store_order_page_controller.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/router/app_routers.dart';
import 'package:xinxuan/vo/common_vo/common_pagination_vo.dart';
import 'package:xinxuan/vo/store_list_vo.dart';
import 'package:xinxuan/vo/store_time_list_vo.dart';
import 'package:common_utils/common_utils.dart';

class PickUpCodePageController extends GetxController {

  final StoreOrderPageController storeOrderPageController = Get.find();

  var orderId = 0.obs;
  var products = <Map<String, dynamic>>[].obs;
  var statusStr = ''.obs;
  var status = 0.obs;

  /// 选中的门店
  var storeId = 0.obs;
  var storeName = ''.obs;
  /// 选中的时间
  var timeValue = ''.obs;
  /// 搜索门店关键词
  String searchTitle = '';
  DateTime? startTime;
  DateTime? endTime;

  /// 门店列表
  var storeListVo = StoreListVo(
    data: [],
    meta: StoreMeta(
      pagination: CommonPagination(
        total: 0,
        currentPage: 1
      )
    )
  ).obs;

  /// 门店可预约时间列表
  var storeTimeListVo = StoreTimeListVo(data: StoreTimeListData(id: 0, bookings: [])).obs;
  
  @override
  void onReady() {
    Map<String, dynamic> argumentsMap = Get.arguments;
    orderId.value = argumentsMap['orderId'];
    products.value = argumentsMap['products'];
    statusStr.value = argumentsMap['statusStr'];
    status.value = argumentsMap['status'];
    getStores();
    super.onReady();
  }

  /// 获取门店列表
  Future<bool> getStores() async {
    storeListVo.value.meta!.pagination!.currentPage = 1;
    StoreListVo tempVo = await HttpUtilService.getStores(page: storeListVo.value.meta!.pagination!.currentPage!, title: searchTitle);
    storeListVo.value = tempVo;
    update();
    return true;
  }

  /// 加载更多门店
  Future<bool> onLoadStores() async {
    if (storeListVo.value.meta!.pagination!.total! <= storeListVo.value.data!.length) {
      return false;
    }
    storeListVo.value.meta!.pagination!.currentPage = storeListVo.value.meta!.pagination!.currentPage! + 1;
    StoreListVo tempVo = await HttpUtilService.getStores(page: storeListVo.value.meta!.pagination!.currentPage!, title: searchTitle, loading: false);
    storeListVo.value.data!.addAll(tempVo.data!);
    update();
    return true;
  }

  getStoreTimeList() async {
    StoreTimeListVo temoVo = await HttpUtilService.getStoreTimeList(id: storeId.value);
    storeTimeListVo.value = temoVo;
    if (temoVo.data!.bookings!.length > 0) {
      startTime = DateTime.parse(temoVo.data!.bookings![0].pickingAt!);
      endTime = DateTime.parse(temoVo.data!.bookings![temoVo.data!.bookings!.length - 1].pickingAt!);
    }
  }

  /// 确认选中时间
  onConfirmTime(DateTime value) {
    String monthStr = '';
    if (value.month < 10) {
      monthStr = '0${value.month}';
    } else {
      monthStr = '${value.month}';
    }
    String dayStr = '';
    if (value.day < 10) {
      dayStr = '0${value.day}';
    } else {
      dayStr = '${value.day}';
    }
    String time = '${value.year}-$monthStr-$dayStr';
    for(var item in storeTimeListVo.value.data!.bookings!) {
      if (item.pickingAt!.contains(time)) {
        if (item.status! <= 0) {
          Get.dialog(MessageDialog(
            message: item.status == 0 ? '$time已预约满，无法预约哦~' : '$time, 无法预约哦~',
            title: '温馨提示',
          ));
          return;
        } 
        timeValue.value = '${value.year}-${value.month}-${value.day}';
        return;
      }
    }
  }

  /// 提交预约
  submitMark() {
    if (storeId.value <= 0) {
      EasyLoading.showToast('请选择预约门店');
      return;
    }
    if (TextUtil.isEmpty(timeValue.value)) {
      EasyLoading.showToast('请选择预约日期');
      return;
    }
    Get.dialog(DeliveryConfirmationDialog(
      storeName: '$storeName', 
      time: '${timeValue.value}', 
      onTap: () async {
        var res = await HttpUtilService.submitStoreMark(orderId: orderId.value, storeId: storeId.value, pickTime: timeValue.value);
        if (res) {
          storeOrderPageController.getStoreOrderList();
          Get.offAndToNamed(
            '${AppRouters.COMMON_PAGE}${AppRouters.STORE_ORDER_PAGE}${AppRouters.STORE_ORDER_DETAIL_PAGE}',
            arguments: {
              'orderId': orderId.value,
              'title': statusStr.value,
              'status': status.value
            }
          );
        }
      }
    ));
  }


}